package lab.cadl.lirui.markdown.core.model

import java.util.*

class MarkdownBuilder {
    private val document: MarkdownDocument = MarkdownDocument(PaperRefDatabase())
    private val sectionStack: Stack<Section> = Stack()

    init {
        sectionStack.push(document)
    }

    fun enterSection(title: String): MarkdownBuilder {
        val parent = sectionStack.peek()
        val seq = parent.subSections.size + 1

        val section = Section(parent)
        section.heading = Heading(parent = section, level = parent.level + 1, seq = seq).title(title)
        sectionStack.push(section)

        return this
    }

    fun nextSection(title: String): MarkdownBuilder {
        val prev = sectionStack.pop()
        val section = Section(prev.parentSection)
        section.heading = Heading(parent = section, level = prev.level, seq = prev.seq + 1, title = title)
        sectionStack.push(section)

        return this
    }

    fun exitSection(): MarkdownBuilder {
        sectionStack.pop()

        return this
    }

    fun build() = document

    fun element(e: AbstractElement): MarkdownBuilder {
        sectionStack.peek().appendChild(e)
        return this
    }

    fun imageBlock(url: String, title: String): MarkdownBuilder {
        val e = ImageBlock(parent = sectionStack.peek(), url = url, title = title, refId = title)
        return element(e)
    }
}